package com.yanyeori.framework.log.config;

import com.yanyeori.framework.log.common.constant.LogConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.util.StringUtils;

/**
 * log4j2获取配置信息，配置系统变量
 *
 * @author chenkuan 2021/3/26
 */
@Order(Ordered.HIGHEST_PRECEDENCE + 19)
public class LogAutoConfig implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment env = event.getEnvironment();
        String appName = env.getProperty("spring.application.name");
        String logPath = env.getProperty("logging.path");
        if (StringUtils.hasLength(appName)) {
            MDC.put(LogConst.APP_NAME, appName);
        } else {
            final Logger logger = LoggerFactory.getLogger(getClass());
            String bannerText = "No spring.application.name is set, the log file name will be [temp.log]";
            if (logger.isWarnEnabled()) {
                logger.warn(bannerText);
            } else {
                System.out.println(bannerText);
            }
        }
        if (StringUtils.hasLength(logPath)) {
            MDC.put(LogConst.LOG_PATH, logPath);
        }
    }
}
